import React, { useEffect, useState } from 'react'
import { get3d } from './../../api/index'
import { Toast, PullToRefresh, List, Image } from 'antd-mobile'

const Index = () => {

  let [weather, setWeather] = useState([])
  let [refresh, setRefresh] = useState(true)

  useEffect(() => {
    const options = {
      enableHighAccuracy: true,
      maximumAge: 10000, // 毫秒
    }
    function onSuccess(position) {
      console.log('dd', position)
      alert(JSON.stringify(position))
      // alert('经度：' + position.coords.longitude + "\n" +
      //   '纬度：' + position.coords.latitude + "\n"
      // );
      const location = position.coords.longitude + "," + position.coords.latitude
      get3d(location).then(res => {
        if (res.code === '200') {
          Toast.show({
            content: '获取天气成功',
            duration: 3000,
          })
          setWeather(res.daily)
        } else {
          Toast.show({
            content: '获取天气失败',
            duration: 3000,
          })
        }
      }).catch(err => {
        Toast.show({
          content: '获取天气失败:' + err.message || '',
          duration: 3000,
        })
      })
    }
    function onError(error) {
      console.log(error)
      alert("Code: " + error.code + "\n Message: " + error.message)
    }
    if (refresh) {
      // alert(JSON.stringify(navigator))
      console.log(JSON.stringify(navigator))
      // 模拟请求
      const position = {
        coords: {
          latitude: 39.9019685,
          longitude: 116.2065455
        }
      }
//      onSuccess(position)

      setRefresh(false)
      navigator.geolocation.getCurrentPosition(onSuccess, onError, options)
    }
  }, [refresh])

  return (
    <div>
      <PullToRefresh
        onRefresh={() => {
          setRefresh(true)
        }}
      >
        <List header='' mode="card">
          {
            weather.map((item, index) => {
              return (
                <List.Item
                  key={index}
                  style={{
                    '--align-items': ''
                  }}
                  prefix={
                    <Image
                      src={require('../../assets/color-64/' + item.iconDay + '.png')}
                      style={{ borderRadius: 5 }}
                      fit="cover"
                      width={60}
                      height={60}
                    />
                  }
                  description={
                    <React.Fragment>
                      <span>温度：{item.tempMin} - {item.tempMax}</span>
                    </React.Fragment>
                  }
                >
                  风向：{item.windDirDay}
                </List.Item>
              )
            })
          }
        </List>
      </PullToRefresh>
    </div>
  )
}

export default Index